<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;
use yii\db\Expression;

/**
 * This is the model class for table "department".
 *
 * @property integer $id
 * @property integer $uuid
 * @property string $name
 * @property integer $level
 * @property integer $parent_id
 * @property integer $sort
 * @property integer $organization_id
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $created_by
 * @property integer $updated_by
 */

class Department extends \yii\db\ActiveRecord
{


    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'department';
    }

    /**
     * create_time, update_time to now()
     * crate_user_id, update_user_id to current login user id
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            // BlameableBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['level', 'parent_id', 'sort', 'created_at', 'updated_at', 'created_by', 'updated_by','organization_id'], 'integer'],
            ['name', 'string', 'max' => 10],
            ['name','required'],

        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'name' => Yii::t('app', 'Department ').Yii::t('app', 'Name'),
            'level' => Yii::t('app', 'Level'),
            'parent_id' => Yii::t('app', 'Parent ').Yii::t('app', 'Department '),
            'sort' => Yii::t('app', 'Sort'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
            'created_by' => Yii::t('app', 'Created By'),
            'updated_by' => Yii::t('app', 'Updated By'),
        ];
    }

    /**
     * Before save.
     * 
     */
    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert))
        {
            if($insert) {
                $this->created_by = Yii::$app->user->id;
                $this->updated_by = Yii::$app->user->id;
                $this->organization_id = Yii::$app->user->identity->organization_id;
                $this->uuid = Yii::$app->uuid->uuid3(\Ramsey\Uuid\Uuid::NAMESPACE_DNS, $this->id.$this->name.time());
            }else{
                $this->updated_by = Yii::$app->user->id;
            }
            return true;
        }
        else
            return false;
    }

    /**
     * After save.
     *
     */
    /*public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        // add your code here
    }*/

    public static function getDepartments(){
        $group_array = Department::find()->select(['id','parent_id','name','level'])->asArray()->all();

        $menu_list = Department::getTree(0, $group_array);
        return $menu_list;
        /*
        $group_list=array();
        if($group_array){
            foreach($group_array as $item){
                $group_list[$item['id']] = $item['name'];
            }
        }
        return $group_list;
        */

    }

    /**
     * Get all catalog order by parent/child with the space before child label
     * Usage: ArrayHelper::map(Catalog::get(0, Catalog::find()->asArray()->all()), 'id', 'label')
     * @param int $parentId  parent catalog id
     * @param array $array  catalog array list
     * @param int $level  catalog level, will affect $repeat
     * @param int $add  times of $repeat
     * @param string $repeat  symbols or spaces to be added for sub catalog
     * @return array  catalog collections
     */
    static public function getTree($parentId = 0, $array = [], $level = 0, $add = 2, $repeat = '　')
    {
        $strRepeat = '';
        // add some spaces or symbols for non top level categories
        if ($level > 1) {
            for ($j = 0; $j < $level; $j++) {
                $strRepeat .= $repeat;
            }
        }

        $newArray = array ();
        //performance is not very good here
        foreach ((array)$array as $v) {
            if ($v['parent_id'] == $parentId) {
                $item = (array)$v;
                $item['name'] = $strRepeat . (isset($v['title']) ? $v['title'] : $v['name']);
                $newArray[] = $item;

                $tempArray = self::getTree($v['id'], $array, ($level + $add), $add, $repeat);
                if ($tempArray) {
                    $newArray = array_merge($newArray, $tempArray);
                }
            }
        }
        return $newArray;
    }

    public static function getName($id){
        if($id && is_numeric($id)){
            $result = static::find()->select(['id','name'])->where(['id'=>$id])->one();
            if(isset($result)){
                return $result->name;
            }
            else{
                return Yii::t('app', 'Not Set');
            }
        }
        return Yii::t('app', 'Not Set');
    }

    public static function getAll()
    {
        return static::find()->where(['organization_id'=>Yii::$app->user->identity->organization_id])->orderBy('sort ASC,id ASC')->asArray()->all();
    }

}
